!function () {
    function setShare(title,desc,url) {
        wx.onMenuShareTimeline({
            title: title,
            link: url,
            imgUrl: Shareimg_url
        });
        wx.onMenuShareAppMessage({
            title: title,
            desc: desc,
            link: url,
            imgUrl: Shareimg_url,
            type: 'link'
        });
    }

    function loginanim() {
        delta+=0.01;
        var d0 = Math.abs(Math.sin(Math.PI/2+delta));
        var d1 = Math.abs(Math.sin(Math.PI/3+delta));
        var d2 = Math.abs(Math.sin(Math.PI/6+delta));
        $$('.login-anim-btn').eq(0).css({'opacity':d0});
        $$('.login-anim-btn').eq(1).css({'opacity':d1});
        $$('.login-anim-btn').eq(2).css({'opacity':d2});
        loginanimid=$$.requestAnimationFrame(loginanim);
    }

    function request(url,method,data,success){
        $$.ajax({
            method:method,
            url:url,
            data:data,
            dataType:'json',
            success:success
        });
    }

    function initPanel() {
        mainView.router.load({url:'panel.html',reload:true});
    }

    function loginscreen() {
        Smapp.prompt('请输入手机号','',function(mobile){
            if (!(/^1\d{10}$/).test(mobile)) {
                Smapp.alert('请输入正确的11位手机号','',loginscreen);
                return;
            }
            Smapp.showIndicator();
            $$.ajax({
                method:'GET',
                url:Fisrtlogin_url,
                data:{mobile:mobile},
                dataType:'json',
                xhrFields:{"withCredentials":true},
                success:function (res) {
                    Smapp.hideIndicator();
                    if (res.code==1){
                        if (res.data.status==1){
                            Globalsls=res.data.data.sls;
                            Globalopenid=res.data.data.openid;
                            initPanel();
                        }else if(res.data.status==2){
                            //不是销售员，跳转申请页面
                            Smapp.modal({
                                title:"",
                                text:"您还不是能量逗代言人，请先申请成为代言人",
                                buttons:[
                                    {
                                        text:"去申请",
                                        onClick: function () {
                                            window.location.href='https://wap.youzan.com/salesman/home/tutorial/index?kdt_id=18168297';
                                        }
                                    }
                                ]
                            });
                            // Smapp.alert('您还不是能量逗代言人，请先申请成为代言人','',function () {
                            //     window.location.href='https://wap.youzan.com/salesman/home/tutorial/index?kdt_id=18168297';
                            // });
                        }else if(res.data.status==3){
                            //session不存在
                            window.location.href='http://api.nldou.com/ucenter/weixinlogin?pid=5328';
                        }
                    }
                }
            });
        },function () {
            loginscreen();
        });
    }

    function checklogin()
    {
        Smapp.showIndicator();
        $$.ajax({
            method:'GET',
            url:Checklogin_url,
            data:{},
            dataType:'json',
            xhrFields:{"withCredentials":true},
            success:function (res) {
                Smapp.hideIndicator();
                if (res.code==1){
                    Globalsls=res.data.sls;
                    Globalopenid=res.data.openid;
                    if (Globalsls=='noauth') loginscreen();
                    else initPanel();
                }else{
                    //session不存在
                    window.location.href='http://api.nldou.com/ucenter/weixinlogin?pid=5328';
                }
            }
        })
    }

    function checkMoney(val)
    {
        return (/^([1-9][0-9]*)|(([0]\.\d?[1-9]{1})|([1-9][0-9]*\.\d?[1-9]{1}))$/).test(val);
    }

    var $$=Dom7;
    var delta=0;//动画速率
    var loginanimid;//动画实例
    // var query = window.location.search;
    var Globalsls;
    // if (query.indexOf('sls=')===-1) Globalsls='noauth';
    // else Globalsls=query.substr((query.indexOf('sls=')+4),6);
    var Globalopenid;
    var Fisrtlogin_url = "http://api.nldou.com/salesman/passport/firstlogin";
    var Checklogin_url = "http://api.nldou.com/salesman/passport/checklogin";
    var Get_coupon_url = "http://api.nldou.com/salesman/coupon/getCoupons";
    var Get_article_url = "http://api.nldou.com/salesman/article/getArticles";
    var Get_article_asset_url = "http://api.nldou.com/salesman/article/getArticleRemainMoney";
    var Demand_money_url = "http://api.nldou.com/salesman/article/demandMoney";
    var Get_post_url = "http://api.nldou.com/salesman/post/getPosts";
    var Initjssdk_url = "http://api.nldou.com/weixinapi/init_wx_jsapi";
    var Initpanel_url = "http://api.nldou.com/salesman/passport/getInfo";
    var Get_article_status_url = "http://api.nldou.com/salesman/article/getArticleStatus";
    var Get_money_record_url = "http://api.nldou.com/salesman/article/getMoneyRecord";
    var Shareimg_url = "http://wap.nldou.com/img/nldou-bg.jpg";
    var Share_url = "http://api.nldou.com/ucenter/weixinlogin?pid=5328";

    loginanimid = $$.requestAnimationFrame(loginanim);

    $$.ajax({
        url:Initjssdk_url,
        method:"GET",
        data: {fromUrl:window.location.href},
        dataType:'json',
        success: function (res) {
            if(res.code==1){
                wx.config({
                    debug: false,
                    appId: res.data.appid,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems']
                });
            }
        }
    });

    wx.ready(function () {
        wx.hideMenuItems({
            menuList: ['menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share:facebook', 'menuItem:share:QZone'
                ,'menuItem:copyUrl', 'menuItem:openWithQQBrowser', 'menuItem:openWithSafari']
        });
        wx.onMenuShareTimeline({
            title: '能量逗代言人中心',
            link: Share_url,
            imgUrl: Shareimg_url
        });
        wx.onMenuShareAppMessage({
            title: '能量逗代言人中心',
            desc: '欢迎加入能量逗代言人的大家庭~~',
            link: Share_url,
            imgUrl: Shareimg_url,
            type: 'link'
        });
    });

    /****Initialize your app****/
    var Smapp = new Framework7({
        animateNavBackIcon: true,
        modalTitle:'代言人',
        modalButtonOk:'确认',
        modalButtonCancel:'取消',
        template7Pages:true,
        swipeBackPage:false,
        pushState:true,
        pushStateSeparator:'#page/'
    });

    /****Add view****/
    var mainView = Smapp.addView('.view-main', {
        dynamicNavbar: true
    });

    Smapp.CouponitemTemplate=Template7.compile($$('script#Couponitem').html());
    Smapp.NocouponTemplate=Template7.compile($$('script#Nocoupon').html());
    Smapp.ArticleitemTemplate=Template7.compile($$('script#Articleitem').html());
    Smapp.PanelheaderTemplate=Template7.compile($$('script#Panelheader').html());
    Smapp.PanelArticleStatusTemplate=Template7.compile($$('script#PanelArticleStatus').html());
    Smapp.MoneyRecorditemTemplate=Template7.compile($$('script#MoneyRecorditem').html());
    Smapp.PostitemTemplate=Template7.compile($$('script#Postitem').html());

    checklogin();
    // if (Globalsls==='noauth') loginscreen();
    // else initPanel();

    $$.cancelAnimationFrame(loginanimid);

    $$(document).on('click','.article-panel-btn',function () {
        mainView.router.load({url:'article.html'});
    });
    $$(document).on('click','.coupon-panel-btn',function () {
        mainView.router.load({url:'coupon.html'});
    });
    $$(document).on('click','.post-panel-btn',function () {
        mainView.router.load({url:'post.html'});
    });
    $$(document).on('click','.post-item',function () {
        var postsrc = $$(this).data('src');
        var popupHTML='<div class="popup">' +
            '<div class="content-block">' +
            '<div class="savetext" style="text-align: center;color: #4c3b3b;font-weight: bold;">' +
            '长按图片保存到相册' +
            '</div>' +
            '<img src="'+postsrc+'" style="width: 80%;margin: 0 10%;">' +
            '<div style="position: absolute;top: 10px;right: 10px;left: auto;bottom: auto;">' +
            '<i href="#" class="close-popup f7-icons color-green" style="font-size: 30px;">close_round_fill</i>' +
            '</div>' +
            '</div>' +
            '</div>';
        Smapp.popup(popupHTML)
    });
    $$(document).on('click','.article-item',function () {
        var model=$$(this).data('artmodel');
        window.location.href="http://api.nldou.com/salesman/article/create/"+model+"."+Globalsls;
    });
    $$(document).on('click','.demand-money-btn',function () {
        var money=$$('#Asset .remain-money').data('money');
        money=parseFloat(money);
        if (money<10){
            Smapp.alert('可提现金额小于10元不可提现','');
            return;
        }
        Smapp.prompt('请输入提现金额','',function (val) {
            if (!checkMoney(val)){
                Smapp.alert('请输入正确的数字','');
                return;
            }
            val=parseFloat(val);
            if (val>money) {
                Smapp.alert('您最多只能提现'+money+'元','');
                return;
            }
            Smapp.showPreloader('提交中');
            val*=100;
            request(Demand_money_url,'GET',{sls:Globalsls,money:val},function (res) {
                Smapp.hidePreloader();
                if (res.data.status==1){
                    Smapp.alert('提交成功','',function () {
                        $$('#Asset .remain-money').html('￥ '+res.data.remainmoney);
                        $$('#Asset .remain-money').data('money',res.data.remainmoney);
                    });
                }
                if (res.data.status==2) Smapp.alert('可提现金额小于10元不可提现','');
                if (res.data.status==3) Smapp.alert('提现金额超过可提现额度','');
            });
        });
    });
    Smapp.onPageInit('Panel',function () {
        $$('.navbar').removeClass('navbar-hidden');
        $$.ajax({
            method:'GET',
            url:Initpanel_url,
            data:{sls:Globalsls},
            dataType:'json',
            xhrFields:{"withCredentials":true},
            success:function (res) {
                if (res.code==1){
                    //console.log(res.data);
                    var html=Smapp.PanelheaderTemplate(res.data);
                    $$('#Panel .panel-header').html(html);
                }else{window.location.href='http://api.nldou.com/ucenter/weixinlogin?pid=5328';}
            }
        });
        request(Get_article_status_url,'GET',{sls:Globalsls},function (res) {
            if (res.code==1){
                //console.log(res.data);
                var html=Smapp.PanelArticleStatusTemplate(res.data);
                $$('#Panel .article-status-wrap').html(html);
            }
        })
    });
    Smapp.onPageInit('Article',function () {
        request(Get_article_url,'POST',{pagesize:10,page:1},function (res) {
            if (res.code==1){
                $$('#Article .infinite-scroll-preloader').remove();
                var html=Smapp.ArticleitemTemplate(res.data.list);
                $$('#Article .Article-wrap ul').html(html);
            }
        });
    });
    Smapp.onPageInit('Asset',function () {
        request(Get_article_asset_url,'GET',{sls:Globalsls},function (res) {
            if (res.code==1){
                var money = '￥ '+res.data.remainmoney;
                $$('#Asset .remain-money').removeClass('preloader');
                $$('#Asset .remain-money').html(money);
                $$('#Asset .remain-money').data('money',res.data.remainmoney)
            }
        });
    });
    Smapp.onPageInit('Moneyrecord',function () {
        request(Get_money_record_url,'GET',{sls:Globalsls},function (res) {
            //console.log(res);
            if (res.code==1){
                var html=Smapp.MoneyRecorditemTemplate(res.data);
                $$('#Moneyrecord .money-record-wrap').html(html);
            }
        });
    });
    Smapp.onPageInit('Coupon',function () {
        request(Get_coupon_url,'GET',{sls:Globalsls},function (res) {
            if (res.code==1){
                $$('#Coupon .infinite-scroll-preloader').remove();
                if (res.data.status==1){
                    var html=Smapp.CouponitemTemplate(res.data.data);
                    $$('#Coupon .coupon-wrap ul').html(html);
                    $$('#Coupon .coupon-item').on('click',function () {
                        var couponid = $$(this).data('couponid');
                        var couponvalue = $$(this).data('couponvalue');
                        mainView.router.load({url:'couponshare.html',context:{couponid:couponid,couponvalue:couponvalue}});
                    });
                }else if(res.data.status==2){
                    var html = Smapp.NocouponTemplate();
                    $$('#Coupon .coupon-wrap').html(html);
                }
            }
        });
    });
    Smapp.onPageInit('Post',function () {
        request(Get_post_url,'POST',{pagesize:10,page:1,sls:Globalsls},function (res) {
            if (res.code==1){
                var html=Smapp.PostitemTemplate(res.data);
                $$('#Post .Post-wrap').html(html);
            }
        });
    });
    Smapp.onPageInit('Couponshare',function () {
        var couponid=$$('#Couponshare').data('couponid');
        var couponvalue=$$('#Couponshare').data('couponvalue');
        var url= 'http://api.nldou.com/ucenter/weixinlogin?pid=5626&page=&param=alias.'+Globalsls+'$'+couponid;
        var title= '点击领取'+couponvalue+'元优惠券';
        var desc = '能量逗益智家庭桌游，快乐教育，与孩子共同成长';
        setShare(title,desc,url);
    });
    Smapp.onPageAfterBack('Couponshare',function () {
        var title= '能量逗代言人中心';
        var desc = '欢迎加入能量逗代言人的大家庭~~';
        setShare(title,desc,Share_url);
    });
}();
